<template>
  <el-dialog
      :title="isEdit ? '编辑子女' : '添加子女'"
      v-model="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
      @close="handleClose"
  >
    <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="child-form"
    >
      <el-form-item label="姓名" prop="childName">
        <el-input v-model="form.childName" placeholder="请输入姓名"/>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入手机号"/>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
            v-model="form.password"
            type="password"
            :placeholder="isEdit ? '不修改请留空' : '请输入密码'"
            show-password
        />
      </el-form-item>
      <el-form-item label="所属社区" prop="communityId">
        <el-select
            v-model="form.communityId"
            placeholder="选择社区"
            filterable
            remote
            :remote-method="filterCommunity"
            :loading="communityLoading"
            clearable
            style="width: 200px"
        >
          <el-option
              v-for="item in filteredCommunityList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="头像" prop="avatar">
        <el-upload
            class="avatar-uploader"
            action="http://127.0.0.1:8080/File/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :headers="uploadHeaders"
            :on-error="handleAvatarError"
        >
          <img v-if="form.avatar" :src="form.avatar" class="avatar" alt=""/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {ref, reactive, watch} from 'vue'
import {ElMessage} from 'element-plus'
import {Plus} from '@element-plus/icons-vue'
import type {FormInstance} from 'element-plus'
import type {Child} from '@/types/child'
import type {Community} from '@/types/community'
import {addChild, updateChild} from '@/api/child'
import {useUserStore} from '@/stores/user'

const props = defineProps<{
  isEdit: boolean
  child?: Child
  communityList: Community[]
}>()

const emit = defineEmits<{
  (e: 'success'): void
}>()

const dialogVisible = ref(false)
const formRef = ref<FormInstance>()

const userStore = useUserStore()

// 创建一个新的响应式表单数据
const form = reactive<Partial<Child>>({
  id: undefined,
  childName: '',
  phone: '',
  password: '',
  communityId: undefined,
  avatar: ''
})

// 社区过滤方法
const filterCommunity = (query: string) => {
  if (query) {
    communityLoading.value = true
    setTimeout(() => {
      filteredCommunityList.value = props.communityList.filter(item => {
        return item.name.includes(query)
      })
      communityLoading.value = false
    }, 200)
  } else {
    filteredCommunityList.value = props.communityList
  }
}

// 创建一个新的响应式对象来存储编辑时的数据
const editData = ref<Partial<Child>>({})
const communityLoading = ref(false)
const filteredCommunityList = ref<Community[]>([])

// 创建表单校验规则
const getRules = (isEdit: boolean) => ({
  childName: [
    {required: false, message: '请输入姓名', trigger: 'blur'},
    {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'}
  ],
  phone: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur'}
  ],
  password: [
    {required: !isEdit, message: '请输入密码', trigger: 'blur'},
    {
      pattern: /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{6,}$/,
      min: 6,
      message: '请输入正确的密码（6位及以上字母+数字组合）',
      trigger: ['blur', 'change']
    }
  ],
  communityId: [
    {required: false, message: '请选择所属社区', trigger: 'change'}
  ]
})

const rules = ref(getRules(props.isEdit))

// 上传请求头
const uploadHeaders = {
  Authorization: `${userStore.token}`
}

// 重置表单数据的方法
const resetForm = () => {
  // 重置表单验证状态
  formRef.value?.resetFields()

  // 重置表单数据
  Object.assign(form, {
    id: undefined,
    childName: '',
    phone: '',
    password: '',
    communityId: undefined,
    avatar: ''
  })

  // 清空编辑数据
  editData.value = {}
}

// 打开对话框
const open = () => {
  // 先重置表单
  formRef.value?.resetFields()
  formRef.value?.clearValidate()

  // 更新验证规则
  rules.value = getRules(props.isEdit)

  // 初始化社区列表
  filteredCommunityList.value = [{id: 0, name: '无'}, ...props.communityList]

  // 设置表单数据
  if (props.isEdit && props.child) {
    // 保存原始数据，包括密码
    editData.value = {...props.child}
    // 设置表单数据，密码字段为空
    const {password, ...rest} = props.child
    Object.assign(form, {
      ...rest,
      password: '' // 编辑时密码默认为空
    })
  } else {
    // 重置为初始值
    Object.assign(form, {
      id: undefined,
      childName: '',
      phone: '',
      password: '',
      communityId: undefined,
      avatar: ''
    })
    // 清空编辑数据
    editData.value = {}
  }

  // 最后显示对话框
  dialogVisible.value = true
}

// 监听社区列表变化
watch(() => props.communityList, (newVal) => {
  filteredCommunityList.value = [...newVal]
}, {immediate: true})

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  // 重置表单
  formRef.value?.resetFields()
  // 清空表单数据
  Object.assign(form, {
    id: undefined,
    childName: '',
    phone: '',
    password: '',
    communityId: undefined,
    avatar: ''
  })
  // 清空编辑数据
  editData.value = {}
}

// 监听对话框显示状态
watch(dialogVisible, (newVal) => {
  if (!newVal) {
    resetForm()
  }
})

// 头像上传成功
const handleAvatarSuccess = (response: any) => {
  // 直接使用 response（已经是上传后的 URL 字符串）
  form.avatar = response.data
  ElMessage.success('头像上传成功')
}

// 头像上传失败
const handleAvatarError = (error: any) => {
  console.error('头像上传失败:', error)
  ElMessage.error('头像上传失败，请重试')
}

// 头像上传前校验
const beforeAvatarUpload = (file: File) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 20

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 20MB!')
  }
  return isJPG && isLt2M
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const submitData = {
          ...form,
          id: props.isEdit ? props.child?.id : undefined
        }

        // 如果是编辑模式且密码为空，则使用原始密码
        if (props.isEdit && !submitData.password) {
          submitData.password = editData.value.password
        }

        // 调用API
        if (props.isEdit) {
          await updateChild(submitData)
          ElMessage.success('更新成功')
        } else {
          await addChild(submitData)
          ElMessage.success('添加成功')
        }

        // 关闭对话框并触发成功事件
        dialogVisible.value = false
        emit('success')
      } catch (error) {
        console.error('提交失败:', error)
      }
    }
  })
}

defineExpose({
  open
})
</script>

<style scoped>
.child-form {
  padding: 20px;
}

.avatar-uploader {
  text-align: center;
}

.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  display: block;
  border-radius: 50%;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
  border-radius: 50%;
}
</style> 